package com.itlong.cloud.controller.sdkV3.base;

import brave.propagation.ExtraFieldPropagation;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.AppCallLiftSaveDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateDeveloperAuthDeviceAuthListDTO;
import com.itlong.cloud.POJO.DTO.property.AppUserUpdateUserProjectStatusDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyAddVisitorDTO;
import com.itlong.cloud.POJO.DTO.sdk.*;
import com.itlong.cloud.POJO.DTO.sdk.sendPush.SendPushMessageDTO;
import com.itlong.cloud.POJO.PO.DeviceElevatorInfoPO;
import com.itlong.cloud.POJO.PO.OperateUserInfoPO;
import com.itlong.cloud.POJO.PO.PropertyUserInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.SDKMessageV3;
import com.itlong.cloud.POJO.VO.SDKMessageVO;
import com.itlong.cloud.POJO.VO.app.robot.AppProjectRobotInfoVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeveloperAuthDeviceAuthVO;
import com.itlong.cloud.POJO.VO.sdk.CloudElevatorSDKDeviceUniqueAllVO;
import com.itlong.cloud.POJO.VO.sdk.SDKServerProjectInfoListPageVO;
import com.itlong.cloud.POJO.VO.sdk.SDKServerProjectInfoListVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LogFeatures;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.controller.sdkV3.elevator.SDKCloudElevatorCTLController;
import com.itlong.cloud.controller.sdkV3.elevator.SDKCloudElevatorRTLController;
import com.itlong.cloud.controller.sdkV3.elevator.SDKCloudRobotNoninductiveController;
import com.itlong.cloud.controller.sdkV3.entrance.SDKCloudEntranceController;
import com.itlong.cloud.controller.sdkV3.face.SDKFaceRecognitionController;
import com.itlong.cloud.controller.sdkV3.intercom.app.SDKCloudTalkAppController;
import com.itlong.cloud.controller.sdkV3.intercom.server.SDKCloudTalkEquipController;
import com.itlong.cloud.controller.sdkV3.intercom.server.SDKCloudTalkMediaController;
import com.itlong.cloud.controller.sdkV3.intercom.server.SDKCloudTalkProjectController;
import com.itlong.cloud.controller.sdkV3.intercom.server.SDKCloudTalkUserController;
import com.itlong.cloud.controller.sdkV3.qrcode.SDKQrCodeController;
import com.itlong.cloud.controller.sdkV3.serverClient.SDKOfflineProjectController;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.enumerate.ecode.*;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.commons.ICloudEntranceServiceClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKRobotClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKServerCloudServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.project.sdk.ICloudTalkSDKServerProjectServiceClient;
import com.itlong.cloud.project.sdk.ISDKServerProjectServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.service.sdkv3.ICheckService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppHomeServiceClient;
import com.itlong.cloud.user.operate.IOperateDeveloperAuthServiceClient;
import com.itlong.cloud.user.operate.IOperatePropertyAccountServiceClient;
import com.itlong.cloud.user.operate.IOperateUserInfoServiceClient;
import com.itlong.cloud.user.sdk.ICloudTalkSDKAppUserServiceClient;
import com.itlong.cloud.user.sdk.ICloudTalkSDKServerUserServiceClient;
import com.itlong.cloud.user.sdk.IFaceSDKVisitorServiceClient;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.*;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <desc>
 * 云设备SDK 共同方法
 * </desc>
 *
 * @createDate 2019/08/27
 */
@RestController
@RequestMapping("/sdkv3/cloud/base")
public class SDKCloudBaseController {


    private static final Logger LOG = LoggerFactory.getLogger(SDKCloudBaseController.class);

    @Autowired
    SDKCloudElevatorCTLController sdkCloudElevatorCTLController;

    @Autowired
    SDKCloudElevatorRTLController sdkCloudElevatorRTLController;

    @Autowired
    SDKCloudEntranceController sdkCloudEntranceController;

    @Autowired
    SDKCloudRobotNoninductiveController sdkCloudRobotNoninductiveController;

    @Autowired
    ICloudElevatorSDKRobotClient iCloudElevatorSDKRobotServiceClient;

    @Autowired
    private ICloudElevatorSDKServerCloudServiceClient iCloudElevatorSDKServerCloudServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    ICloudEntranceServiceClient iCloudEntranceServiceClient;

    @Autowired
    ICloudTalkSDKServerUserServiceClient iCloudTalkSDKServerUserServiceClient;

    @Autowired
    IOperatePropertyAccountServiceClient iOperatePropertyAccountServiceClient;

    @Autowired
    ISDKServerOldUserServiceClient iSDKServerUserServiceClient;

    @Autowired
    IAppHomeServiceClient iAppHomeServiceClient;

    @Autowired
    RedisService redisService;

    @Autowired
    ISDKServerOldUserServiceClient iSDKUserServiceClient;

    @Autowired
    ICloudTalkSDKAppUserServiceClient iCloudTalkSDKAppUserServiceClient;

    @Autowired
    ICloudTalkSDKServerProjectServiceClient iCloudTalkSDKServerProjectServiceClient;

    @Autowired
    SDKQrCodeController sdkQrCodeController;

    @Autowired
    SDKCloudTalkUserController sdkCloudTalkUserController;

    @Autowired
    SDKOfflineProjectController sdkServerProjectController;

    @Autowired
    SDKCloudTalkEquipController sdkCloudTalkEquipController;

    @Autowired
    SDKCloudTalkProjectController sdkCloudTalkProjectController;

    @Autowired
    SDKCloudTalkAppController sdkCloudTalkAppController;

    @Autowired
    IOperateDeveloperAuthServiceClient iOperateDeveloperAuthServiceClient;

    @Autowired
    SDKFaceRecognitionController sdkFaceRecognitionController;

    @Autowired
    SDKCloudTalkMediaController sdkCloudTalkMediaController;

    @Autowired
    IFaceSDKVisitorServiceClient iFaceSDKVisitorServiceClient;

    @Autowired
    IOperateUserInfoServiceClient iOperateUserInfoServiceClient;

    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    ISDKServerProjectServiceClient isdkServerProjectServiceClient;

    @Autowired
    ICheckService iCheckService;

    @Value("${" + PlatformConstants.APP_USER_TOKEN_KEY + "}")
    private String APP_USER_TOKEN_KEY;

    @Value("${" + PlatformConstants.ROBOTGO_APP_SECRET + "}")
    private String APP_SECRET;

    /**
     * <desc>
     * SDK开发者认证
     * <desc/>
     *
     * @param encryptScript 加密入参
     * @param appId         开发者账号
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/09/16
     */
    @ResponseBody
    @PostMapping("/developerLogin")
//    @LoggerInfo(operateDesc = LogDescConstant.SDK_DEVELOPER_LOGIN_LOG_DESC)
    @UnAuthAccessRequired
    @LogFeatures("SDK开发者认证")
    public Object developerLogin(String encryptScript, String appId, String encryptType) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        long requestTime = DateUtil.getTimestamp();
        String responseTimestamp = requestTime + "";
        PropertyUserInfoPO propertyUserInfoPO = null;
        try {
            if (StringUtils.isBlank(appId) || StringUtils.isBlank(encryptScript)) {
                LOG.error("appId和密文不能为空！", ErrorTypeEnum.PARAMETER_ANOMALY.getName());
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), "", responseTimestamp, "");//此时没有加密签名直接明文返回报错信息
            }
            //设置解密方式默认值
            if (null == encryptType) {
                encryptType = EncryptUtil.AES;
            }
            request.setAttribute("appId", appId);
            //获取开发者信息
            propertyUserInfoPO = iSDKUserServiceClient.getPropertyUserByAppId(appId);
            //无此开发者信息时或开发者密码不正确时
            if (propertyUserInfoPO == null || StringUtils.isBlank(propertyUserInfoPO.getAppsecret())) {
                LOG.error("开发者账号或密钥有误！", ErrorTypeEnum.VERIFY_ANOMALY.getName());
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_PARAM_APPID_APPSECRET_ERR.getErrorCode(), "", responseTimestamp, "");//此时没有加密签名直接明文返回报错信息
            }
            if (propertyUserInfoPO.getStatus() != 1) {
                LOG.error("开发者已禁用！", ErrorTypeEnum.VERIFY_ANOMALY.getName());
                return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVELOPER_STATUS_ERR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret(), encryptType);
            }
            //设置本次登录开发者解密方式 存入token中
            propertyUserInfoPO.setEncryptType(encryptType);
//            CloudDeviceSDKDTO dto = new CloudDeviceSDKDTO();
            //校验解密方式参数是否是0和1
            if (!EncryptUtil.AES.equals(encryptType) && !EncryptUtil.SMS.equals(encryptType)) {
                LOG.error("encryptType不符合规范,{},encryptType:{}！", ErrorTypeEnum.PARAMETER_ANOMALY.getName(), encryptType);
                return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(SDKV3ErrorCodeEnum.ENCRYPT_TYPE_VERIFY_ERROR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret(), encryptType);
            }
            //解密参数
            String encryptResult = EncryptUtil.decrypt(encryptScript, propertyUserInfoPO.getAppsecret(), encryptType);
            if (StringUtils.isBlank(encryptResult)) {
                LOG.error("解密失败!", ErrorTypeEnum.VERIFY_ANOMALY.getName());
                return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(SDKV3ErrorCodeEnum.ENCRYPT_ERROR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret(), encryptType);
            }
            Map<String, Object> params;
            //转换解密参数为json
            JSONObject jsStr = JSONObject.parseObject(encryptResult);//入参转json
            String requestId;
            String robotId;
            String timestamp;
            try {
                params = JsonUtil.toObject(jsStr.toString(), HashMap.class);
                requestId = Optional.ofNullable(params.get("requestId")).orElse("").toString();
                robotId = Optional.ofNullable(params.get("robotId")).orElse("").toString();
                timestamp = Optional.ofNullable(params.get("timestamp")).orElse("").toString();
                String sign = Optional.ofNullable(params.get("sign")).orElse("").toString();
                //设置日志
                MDC.put(PlatformConstants.REQUEST_ID, requestId);
                //将请求ID放入sleuth中 开发者认证不走拦截器 需手动设置
                ExtraFieldPropagation.set(PlatformConstants.REQUEST_ID, new String(requestId.getBytes(StandardCharsets.UTF_8)));
                //保存生成操作日志所需信息 详细描述和接口类别
                request.setAttribute("remark", "appId:" + appId + "|" + "appSecret:" + params.get("appSecret") + "robotId:" + params.get("robotId"));
                request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
                //参数校验
                if (requestId.length() > 32 || requestId.length() < 1) {
                    LOG.error("requestId长度不符合规范，应该为1-32位！,{},requestId:{}", ErrorTypeEnum.PARAMETER_ANOMALY.getName(), requestId);
                    return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(SDKV3ErrorCodeEnum.REQUEST_ID_LENGTH_ERROR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret(), encryptType);
                }
                if (!timestamp.matches("[0-9]{13}")) {
                    LOG.error("timestamp不符合规范,{},timestamp:{}！", ErrorTypeEnum.PARAMETER_ANOMALY.getName(), timestamp);
                    return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(SDKV3ErrorCodeEnum.TIMESTAMP_VERIFY_ERROR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret(), encryptType);
                }
                if (StringUtils.isEmpty(sign)) {
                    LOG.error("sign不符合规范,{},sign:{}！", ErrorTypeEnum.PARAMETER_ANOMALY.getName(), sign);
                    return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(SDKV3ErrorCodeEnum.SIGN_VERIFY_ERROR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret(), encryptType);
                }
                //验签
                params.remove("sign");
                if (!EncryptUtil.checkSDKV3Sign(params, propertyUserInfoPO.getAppsecret(), sign, encryptType)) {
                    LOG.error("验签失败！", ErrorTypeEnum.VERIFY_ANOMALY.getName());
                    return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_SIGN_ERROR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret(), encryptType);
                }
                if (StringUtils.isEmpty(robotId)) {
                    LOG.error("机器人编号不能为空！", ErrorTypeEnum.PARAMETER_ANOMALY.getName());
                    return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(SDKV3ErrorCodeEnum.ROBOT_ID_VERIFY_ERROR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret(), encryptType);
                }
                //获取开发者授权机器人编号
                String robots = iSDKServerUserServiceClient.getRobotDevelopRobotInfo(appId);
                boolean isAuth = false;
                if (StringUtils.isNotEmpty(robots)) {
                    String[] robotsArr = robots.split(",");
                    for (String r : robotsArr
                    ) {
                        if (r.equals(robotId)) {
                            isAuth = true;
                            break;
                        }
                    }
                }
                //判断传入编号是否已授权
                if (!isAuth) {
                    LOG.error("当前开发者未授权该机器人,{},appid:{},robotId:{}！", ErrorTypeEnum.VERIFY_ANOMALY.getName(), appId, robotId);
                    return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_SDK_ROBOT_ID_NO_AUTH_ERR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret(), encryptType);
                }
                //获取项目编号
                String projectId = robotId.substring(0, 8);
                Integer projectStatus = iOperateProjectServiceClient.getProjectStatus(projectId);
                //判断项目是否启用
                if (!"1".equals(projectStatus + "")) {
                    LOG.error("项目未启用！", ErrorTypeEnum.VERIFY_ANOMALY.getName());
                    return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(SDKV3ErrorCodeEnum.PROJECT_IS_NOT_ACTIVATED.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret(), encryptType);
                }
                //查询项目信息
                Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(projectId, appId);
                //判断项目是否过期
                SDKMessageV3 checkRes = iCheckService.check2(requestId, requestTime, AuthStatus);
                if (checkRes.getMsgCode() != 0) {
                    LOG.error("开发者授权项目已过期！", ErrorTypeEnum.VERIFY_ANOMALY.getName());
                    return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(SDKV3ErrorCodeEnum.AUTH_TIME_ERROR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret(), encryptType);
                }
                //将机器人id存入token 后面传入机器人id会和token里面的比对
                propertyUserInfoPO.setRobotId(robotId);
            } catch (Exception e) {
                LOG.error("系统异常！,{},{}", ErrorTypeEnum.SYSTEM_ANOMALY.getName(), e);
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_INPUT_PARAM_ERR.getErrorCode(), "", responseTimestamp, "");//json格式解析失败
            }
            //生成token
            String token = iCloudTalkSDKAppUserServiceClient.developerLogin(propertyUserInfoPO, robotId);
            LOG.info("登录成功！token:{},requestId:{},appId:{},timestamp:{}", token, requestId, appId, timestamp);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            request.setAttribute("token", token);

            Map<String, Object> signMap = new HashMap<>();
            signMap.put("data", new JSONObject(map));//签名使用json格式内容进行

            return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), requestId, responseTimestamp,
                    EncryptUtil.getSDKV3Sign(signMap, propertyUserInfoPO.getAppsecret(), encryptType, requestId, responseTimestamp), map), propertyUserInfoPO.getAppsecret(), encryptType);
        } catch (JSONException e) {
            LOG.error("解密异常，json解析失败,{}", ErrorTypeEnum.SYSTEM_ANOMALY.getName(), e);
            return EncryptUtil.getEncryptResultSDKV3(new SDKMessageVO(SDKV3ErrorCodeEnum.ENCRYPT_ERROR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret(), encryptType);
        } catch (Exception e) {
            LOG.error("SDK开发者认证失败,{},{}", ErrorTypeEnum.SYSTEM_ANOMALY.getName(), e);
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_developerLogin】SDK开发者认证", e);
        }
    }

    /**
     * <desc>
     * 获取设备信息
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/09/16
     */
    @ResponseBody
    @PostMapping("/getDeviceInfo")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_CLOUD_DEVICE_UNIQUE_LOG_DESC)
    @LogFeatures("获取设备信息")
    public Object getDeviceKey() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String requestId = Optional.ofNullable(request.getAttribute("requestId")).orElse("").toString();
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            dto.setAppId(request.getAttribute("appId").toString());
            dto.setAppSecret(request.getAttribute("appSecret").toString());
            String responseTimestamp = new Date().getTime() + "";
            dto.setResponseTimestamp(responseTimestamp);
            LOG.info("======getDeviceKey获取设备唯一标识============入参================>{}", null == dto ? "" : dto.toString());
            if (StringUtils.isBlank(dto.getProjectId())) {
                LOG.error("项目编号不能为空！", ErrorTypeEnum.PARAMETER_ANOMALY.getName());
                return new SDKMessageVO(SDKV3ErrorCodeEnum.PROJECT_ID_NOT_SET.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
            }
            //封装不同设备类型接口参数，调用对应接口 将设备编号分类存放到map中
            Map<String, List<String>> deviceUnique = new HashMap<>();
            Map<String, Object> map = new HashMap<>();
            //云电梯机器人对云端
            dto.setRobotDevelopDeviceType(2);
            dto.setDeviceType("1");
            map.put("1", sdkCloudElevatorRTLController.getElevatorKey(dto));
            //云电梯云端对云端
            dto.setDeviceType("2");
            dto.setRobotDevelopDeviceType(null);
            map.put("2", sdkCloudElevatorCTLController.getElevatorKey(dto));
//            //云门禁
//            dto.setDeviceType("3");
//            dto.setRobotDevelopDeviceType(null);
//            map.put("3", sdkCloudEntranceController.getEntranceKey(dto));
            //机器人无感
            dto.setRobotDevelopDeviceType(1);
            dto.setDeviceType("4");
            map.put("4", sdkCloudElevatorRTLController.getElevatorKey(dto));
            //将接口返回对象进行封装转换
            map.forEach((k, v) -> {
                if (v instanceof List) {
                    List<String> tmp = (List<String>) v;
                    deviceUnique.put(k, tmp);
                }
            });
            //调用获取设备信息方法
            return getDeviceInfo(dto, request, responseTimestamp, requestId, deviceUnique);
        } catch (Exception e) {
            LOG.error("获取设备信息异常", ErrorTypeEnum.SYSTEM_ANOMALY.getName());
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getDeviceKey】获取设备唯一标识异常", e);
        }
    }

    /**
     * <desc>
     * 获取设备信息
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/09/17
     */
    public Object getDeviceInfo(CloudDeviceSDKDTO dto, HttpServletRequest request, String responseTimestamp, String requestId, Map<String, List<String>> deviceUniques) throws Exception {
        //分别获取对应设备类型下设备编号查询的设备信息
        List<CloudElevatorSDKDeviceUniqueAllVO> deviceInfo = new ArrayList<>();
        List<Object> os = new ArrayList<>();
        //云电梯机器人对云端
        dto.setRobotDevelopDeviceType(2);
        dto.setDeviceType("1");
        List<String> deviceUnique = Optional.ofNullable(deviceUniques.get("1")).orElse(new ArrayList<>());
        if (!CollectionUtils.isEmpty(deviceUnique)) {
            dto.setDeviceUnique(StringUtils.join(deviceUnique, ","));
            if (StringUtils.isNotEmpty(dto.getDeviceUnique().trim())) {
                os.add(sdkCloudElevatorRTLController.getElevatorInfo(dto));
            }
        }
        //云电梯云端对云端
        dto.setDeviceType("2");
        dto.setRobotDevelopDeviceType(null);
        deviceUnique = Optional.ofNullable(deviceUniques.get("2")).orElse(new ArrayList<>());
        if (!CollectionUtils.isEmpty(deviceUnique)) {
            dto.setDeviceUnique(StringUtils.join(deviceUnique, ","));
            if (StringUtils.isNotEmpty(dto.getDeviceUnique().trim())) {
                os.add(sdkCloudElevatorCTLController.getElevatorInfo(dto));
            }
        }
//        //云门禁
//        dto.setDeviceType("3");
//        dto.setRobotDevelopDeviceType(null);
//        deviceUnique = Optional.ofNullable(deviceUniques.get("3")).orElse(new ArrayList<>());
//        if (!CollectionUtils.isEmpty(deviceUnique)) {
//            dto.setDeviceUnique(StringUtils.join(deviceUnique, ","));
//            if (StringUtils.isNotEmpty(dto.getDeviceUnique().trim())) {
//                os.add(sdkCloudEntranceController.getEntranceInfo(dto));
//            }
//        }
        //机器人无感通行
        dto.setRobotDevelopDeviceType(1);
        dto.setDeviceType("4");
        dto.setRobotDevelopDeviceType(null);
        deviceUnique = Optional.ofNullable(deviceUniques.get("4")).orElse(new ArrayList<>());
        if (!CollectionUtils.isEmpty(deviceUnique)) {
            dto.setDeviceUnique(StringUtils.join(deviceUnique, ","));
            if (StringUtils.isNotEmpty(dto.getDeviceUnique().trim())) {
                os.add(sdkCloudRobotNoninductiveController.getElevatorInfo(dto));
            }
        }
//        //云对讲
//        dto.setDeviceType("5");
//        deviceUnique.clear();
//        for (List<String> item : deviceUniques.values()) {
//            deviceUnique.addAll(item);
//        }
//        if (!CollectionUtils.isEmpty(deviceUnique)) {
//            dto.setDeviceUnique(StringUtils.join(deviceUnique, ","));
//            dto.setRobotDevelopDeviceType(null);
//            if (StringUtils.isNotEmpty(dto.getDeviceUnique().trim())) {
//                os.add(sdkCloudTalkEquipController.getCloudTalkDeviceList(dto));
//            }
//        }
        //封装上面接口调用返回值 统一转回为CloudElevatorSDKDeviceUniqueAllVO类
        for (Object o : os) {
            if (null != o) {
                //判断接口返回是List类型
                if (o instanceof List) {
                    //转换为CloudElevatorSDKDeviceUniqueAllVO对象
                    List<CloudElevatorSDKDeviceUniqueAllVO> tmp = JSONObject.parseArray(JSON.toJSONString(o), CloudElevatorSDKDeviceUniqueAllVO.class);
                    deviceInfo.addAll(tmp);
                }
                //判断接口返回是page类型
                if (o instanceof Page) {
                    Page page = (Page) o;
                    List rows = Optional.ofNullable(page).orElse(new Page<>()).getRows();
                    //转换为CloudElevatorSDKDeviceUniqueAllVO对象
                    List<CloudElevatorSDKDeviceUniqueAllVO> tmp = JSONObject.parseArray(JSON.toJSONString(rows), CloudElevatorSDKDeviceUniqueAllVO.class);
                    deviceInfo.addAll(tmp);
                }
            }
        }
        //将绑定群控器的设备排在前面 去除重复设备
        Comparator<CloudElevatorSDKDeviceUniqueAllVO> cController = Comparator.comparing(CloudElevatorSDKDeviceUniqueAllVO::getControllerDeviceUnique, Comparator.nullsLast(String::compareTo));
        deviceInfo = deviceInfo.stream().sorted(cController).collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getDeviceUnique()))), ArrayList::new));
        return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), requestId, responseTimestamp, null, deviceInfo);
    }

    /**
     * <desc>
     * 获取设备状态
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/09/17
     */
    @ResponseBody
    @PostMapping("/getDeviceStatus")
    public Object gerDeviceStatus() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            dto.setAppId(request.getAttribute("appId").toString());
            dto.setAppSecret(request.getAttribute("appSecret").toString());
            String responseTimestamp = new Date().getTime() + "";
            dto.setResponseTimestamp(responseTimestamp);
            LOG.info("======gerDeviceStatus获取设备状态============入参================>{}", null == dto ? "" : dto.toString());

            if (StringUtils.isBlank(dto.getDeviceType()) || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getDeviceUnique())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
            }
            switch (dto.getDeviceType()) {
                //云电梯机器人对云端
                case "1":
                    dto.setRobotDevelopDeviceType(2);
                    return sdkCloudElevatorRTLController.getElevatorOftenStatus(dto);
                //云门禁
                case "3":
                    return sdkCloudEntranceController.getEntranceStatus(dto);
                //机器人无感
                case "4":
                    dto.setRobotDevelopDeviceType(1);
                    return sdkCloudElevatorRTLController.getElevatorOftenStatus(dto);

                //云对讲
                case "5":
                    dto.setDeviceType("1");
                    return sdkCloudTalkEquipController.getCloudTalkAppStatus(dto);


                //一体式人脸识别仪（目前设备只集成阿里云）
                case "7":
                    dto.setDeviceType("7");
                    return sdkFaceRecognitionController.getFaceRecognitionStatus(dto);
                //人脸平板
                case "8":
                    dto.setDeviceType("3");
                    return sdkFaceRecognitionController.getFaceRecognitionStatus(dto);

            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), dto.getRequestId(), responseTimestamp, dto.getAppSecret()), null);
        } catch (Exception e) {
            throw new DataAccessException("【SDK_基类_gerDeviceStatus】获取设备状态异常", e);
        }
    }


    /**
     * <desc>
     * 电梯楼层开放或登记
     * <desc/>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019/09/17
     */
    @PostMapping(value = "/openOrAutoRegister")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_AUTO_REGISTER)
    @ResponseBody
    public Object openOrAutoRegister() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            dto.setAppId(request.getAttribute("appId").toString());
            dto.setAppSecret(request.getAttribute("appSecret").toString());
            String responseTimestamp = new Date().getTime() + "";
            LOG.info("======openOrAutoRegister电梯楼层开放或登记============入参================>{}", null == dto ? "" : dto.toString());

            if (StringUtils.isBlank(dto.getDeviceType()) || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getDeviceUnique())
                    || StringUtils.isBlank(dto.getFloors()) || dto.getSeconds() == null) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
            }

            SDKMessageVO messageVO = null;
            switch (dto.getDeviceType()) {
                //云电梯机器人对云端
                case "1":
                    dto.setRobotDevelopDeviceType(2);
                    messageVO = (SDKMessageVO) sdkCloudElevatorRTLController.publicParamCheck(dto);
                    break;
                //云电梯云端对云端
                case "2":
                    messageVO = (SDKMessageVO) sdkCloudElevatorCTLController.publicParamCheck(dto);
                    break;
            }
            if (messageVO != null) {
                messageVO.setTimestamp(responseTimestamp);
                LOG.info("======openOrAutoRegister电梯楼层开放或登记messageVO============出参================>{}", null == messageVO ? "" : messageVO.toString());

                return messageVO;
            }

            DeviceElevatorInfoPO po = iCloudElevatorSDKServerCloudServiceClient.getElevatorByDeviceUnique(dto.getDeviceUnique());
            if ("1".equals(dto.getDeviceType())) {//云电梯设备判断,标准版不支持机器人呼梯
                if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 1) {//设备属性配置 ：1标准 2云机器人 3全功能
                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
                }
            } else if ("2".equals(dto.getDeviceType())) {//云电梯设备判断,云机器人版不支持云端功能
                if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 2) {//设备属性配置 ：1标准 2云机器人 3全功能
                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
                }
            }

            //获取真实楼层
            Map<String, Object> floor = iCloudElevatorSDKServerCloudServiceClient.getFloorNumAndNaturalFloorByLogicFloor(dto.getFloors(),
                    dto.getDeviceUnique());
            if (floor == null || floor.get("floors") == null || floor.get("naturals") == null) {
                return new SDKMessageVO(CloudElevarotErrorCodeEnum.CLOUD_FLOOR_ERROR.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
            }
            //调用IOT呼梯
            iAppDeviceServiceClient.openOrAutoRegister(dto.getDeviceUnique(),
                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                    floor.get("floors").toString(), CloudElevatorCallTypeEnum.IN.getType(), dto.getSeconds(), CallElevatorSourceTypeEnum.ROBOT.getType(), "1", null);
            //装配呼梯记录对象
            AppCallLiftSaveDTO saveDTO = new AppCallLiftSaveDTO();
            saveDTO.setDeviceUnique(dto.getDeviceUnique());
            saveDTO.setToFloor(floor.get("naturals").toString());
            saveDTO.setProjectId(dto.getProjectId());
            saveDTO.setSource(CallElevatorRecordSourceEnum.ROBOT.getType());
            saveDTO.setUserId(dto.getAppId());
            iAppHomeServiceClient.saveCallLiftRecord(saveDTO);
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), responseTimestamp, Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), dto.getRequestId(), responseTimestamp, dto.getAppSecret()));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_openOrAutoRegister】电梯楼层开放或登记异常", e);
        }
    }

    /**
     * <desc>
     * 设置专梯模式
     * <desc/>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019-09-18
     */
    @RequestMapping(value = "/setCloudElevatorSpecialUseModel", method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.SDK_BASE_SET_CLOUD_ELEVATOR_SPECIAL_USE_MODEL)
    @ResponseBody
    public Object setCloudElevatorSpecialUseModel() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            dto.setAppId(request.getAttribute("appId").toString());
            dto.setAppSecret(request.getAttribute("appSecret").toString());
            String responseTimestamp = new Date().getTime() + "";
            if (StringUtils.isBlank(dto.getDeviceType()) || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getDeviceUnique())
                    || StringUtils.isBlank(dto.getModel())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
            }
            LOG.info("======setCloudElevatorSpecialUseModel设置专梯模式============出参================>{}", null == dto ? "" : dto.toString());

            SDKMessageVO messageVO = null;
            switch (dto.getDeviceType()) {
                //云电梯机器人对云端
                case "1":
                    dto.setRobotDevelopDeviceType(2);
                    messageVO = (SDKMessageVO) sdkCloudElevatorRTLController.publicParamCheck(dto);
                    break;
                //云电梯云端对云端
                case "2":
                    messageVO = (SDKMessageVO) sdkCloudElevatorCTLController.publicParamCheck(dto);
                    break;
            }
            if (messageVO != null) {
                messageVO.setTimestamp(responseTimestamp);
                LOG.info("======setCloudElevatorSpecialUseModel设置专梯模式messageVO============出参================>{}", null == messageVO ? "" : messageVO.toString());
                return messageVO;
            }
            DeviceElevatorInfoPO po = iCloudElevatorSDKServerCloudServiceClient.getElevatorByDeviceUnique(dto.getDeviceUnique());
            if ("1".equals(dto.getDeviceType())) {//云电梯设备判断,标准版不支持机器人呼梯
                if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 1) {//设备属性配置 ：1标准 2云机器人 3全功能
                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
                }
            } else if ("2".equals(dto.getDeviceType())) {//云电梯设备判断,云机器人版不支持云端功能
                if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 2) {//设备属性配置 ：1标准 2云机器人 3全功能
                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
                }
            }

            iAppDeviceServiceClient.setCloudElevatorSpecialUseModel(dto.getDeviceUnique(), dto.getModel());
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), responseTimestamp, Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), dto.getRequestId(), responseTimestamp, dto.getAppSecret()));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_setCloudElevatorSpecialUseModel】设置专梯模式异常", e);
        }
    }

    /**
     * <desc>
     * 项目信息列表
     * <desc/>
     *
     * @return MessageVO   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/05/23
     */
    @RequestMapping(path = "/getProjectInfo", method = RequestMethod.POST)
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_PROJECT_INFO_LOG_DESC)
    @ResponseBody
    public Object getProjectInfo() {
        SDKMessageVO messageVO;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudTalkSDKServerGetProjectInfoPageDTO pageDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerGetProjectInfoPageDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", request.getAttribute("appId").toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            pageDTO.setAppId(request.getAttribute("appId").toString());
            String responseTimestamp = new Date().getTime() + "";
            //判断接入凭证
            if (StringUtils.isBlank(pageDTO.getAppId())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), pageDTO.getRequestId(), responseTimestamp, "");
            }
            Page<SDKServerProjectInfoListPageVO> pageVO = iCloudTalkSDKServerProjectServiceClient.getProjectList(pageDTO);
            SDKServerProjectInfoListVO sdkServerProjectInfoListVO = new SDKServerProjectInfoListVO();
            sdkServerProjectInfoListVO.setTotalNumber(pageVO.getPage().getTotalNumber());
            sdkServerProjectInfoListVO.setProjectInfoArr(pageVO.getRows());
            Map<String, Object> signMap = new HashMap<>();
            signMap.put("data", JSON.toJSONString(pageVO));
            messageVO = new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), pageDTO.getRequestId(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(signMap, pageDTO.getRequestId(), responseTimestamp, request.getAttribute("appSecret").toString()), pageVO);
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getProjectInfo】获取项目信息列表失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     * 添加或更新楼栋信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author jiaqi.X
     * @createDate 2019/11/06
     */
    @ResponseBody
    @PostMapping(path = "/addOrUpdateBuild")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_BUILD_ADD_OR_UPDATE_LOG_DESC)
    public Object addOrUpdateBuilds() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String responseTimestamp = new Date().getTime() + "";
            if (dto == null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getBuildJson())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
            }
            //如果为人脸识别API则需鉴权
//            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
//                //权限判断
//                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
//                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
//                }
//                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
//            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            if (dto.getDeviceType() != null && dto.getDeviceType().equals(SdkSourceTypeEnum.CLOUD_TALK.getType())) {
                request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            }

            Map<String, Object> result = (HashMap) sdkCloudTalkProjectController.cloudTalkSDKAddOrUpdateBuild(dto);
            Integer count = Integer.valueOf(result.get("count").toString());
            JSONArray errArray = result.get("errArray") != null ? JSONArray.parseArray(result.get("errArray").toString()) : new JSONArray();
            String errStr = "";
            if (errArray.size() > 0) {
                errStr = ",未添加或更新的异常数据：" + errArray.toJSONString();
            }
            if (count > 0) {
                return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                        Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), dto.getRequestId(), dto.getResponseTimestamp(), dto.getAppSecret()), (Object) String.format("%s%s", "本次总共添加或更新了：" + count + " 条数据", errStr));
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), dto.getRequestId(), dto.getResponseTimestamp(), dto.getAppSecret()), (Object) ("添加的数据已存在,或存在异常的数据" + errStr));

        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_addOrUpdateBuilds】添加楼栋信息失败", e);
        }
    }

    /**
     * <desc>
     * 添加或更新单元信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author jiaqi.X
     * @createDate 2019/11/06
     */
    @ResponseBody
    @PostMapping(path = "/addOrUpdateUnit")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_UNIT_ADD_OR_UPDATE_LOG_DESC)
    public Object addOrUpdateUnits() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String responseTimestamp = new Date().getTime() + "";
            if (dto == null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getUnitJson())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
            }
            //如果为人脸识别API则需鉴权
//            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
//                //权限判断
//                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
//                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
//                }
//                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
//            }

            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            if (dto.getDeviceType() != null && dto.getDeviceType().equals(SdkSourceTypeEnum.CLOUD_TALK.getType())) {
                request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            }

            Map<String, Object> result = (HashMap) sdkCloudTalkProjectController.cloudTalkSDKAddOrUpdateUnit(dto);
            Integer count = Integer.valueOf(result.get("count").toString());
            JSONArray errArray = result.get("errArray") != null ? JSONArray.parseArray(result.get("errArray").toString()) : new JSONArray();
            String errStr = "";
            if (errArray.size() > 0) {
                errStr = ",未添加或更新的异常数据：" + errArray.toJSONString();
            }
            if (count > 0) {
                return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                        Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), dto.getRequestId(), dto.getResponseTimestamp(), dto.getAppSecret()), (Object) String.format("%s%s", "本次总共添加或更新了：" + count + " 条数据", errStr));
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), dto.getRequestId(), dto.getResponseTimestamp(), dto.getAppSecret()), (Object) ("添加的数据已存在,或存在异常的数据" + errStr));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_addOrUpdateUnits】添加单元信息失败", e);
        }
    }


    /**
     * <desc>
     * 添加或修改房间信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author jiaqi.X
     * @createDate 2019/11/06
     */
    @ResponseBody
    @PostMapping(path = "/addOrUpdateRoom")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_ROOM_ADD_OR_UPDATE_LOG_DESC)
    public Object addOrUpdateRooms() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String responseTimestamp = new Date().getTime() + "";
            if (dto == null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getRoomJson())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
            }
            //如果为人脸识别API则需鉴权
//            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
//                //权限判断
//                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
//                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
//                }
//                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
//            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            if (dto.getDeviceType() != null && dto.getDeviceType().equals(SdkSourceTypeEnum.CLOUD_TALK.getType())) {
                request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            }

            //云对讲
            Map<String, Object> result = (HashMap) sdkCloudTalkProjectController.cloudTalkSDKAddOrUpdateRoom(dto);
            Integer count = Integer.valueOf(result.get("count").toString());
            JSONArray errArray = result.get("errArray") != null ? JSONArray.parseArray(result.get("errArray").toString()) : new JSONArray();
            String errStr = "";
            if (errArray.size() > 0) {
                errStr = ",未添加或更新的异常数据：" + errArray.toJSONString();
            }
            if (count > 0) {
                return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                        Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), dto.getRequestId(), dto.getResponseTimestamp(), dto.getAppSecret()), (Object) String.format("%s%s", "本次总共添加或更新了：" + count + " 条数据", errStr));
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), dto.getRequestId(), dto.getResponseTimestamp(), dto.getAppSecret()), (Object) ("添加的数据已存在,或存在异常的数据" + errStr));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_addOrUpdateRooms】添加或更新房间信息失败", e);
        }
    }

    /**
     * <desc>
     * 查询项目楼栋信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/07
     */
    @ResponseBody
    @PostMapping(path = "/getBuildList")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_BUILD_GET_LIST_LOG_DESC)
    public Object getBuildList() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String responseTimestamp = new Date().getTime() + "";
            dto.setResponseTimestamp(responseTimestamp);
            if (dto == null || StringUtils.isBlank(dto.getProjectId())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
            }
            if (StringUtils.isBlank(dto.getCurrentPage())) {
                dto.setCurrentPage("1");
            }
            if (StringUtils.isBlank(dto.getPageSize())) {
                dto.setPageSize("15");
            }
            //如果为人脸识别API则需鉴权
//            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
//                //权限判断
//                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
//                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
//                }
//                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
//            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            if (dto.getDeviceType() != null && dto.getDeviceType().equals(SdkSourceTypeEnum.CLOUD_TALK.getType())) {
                request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            }
            return sdkCloudTalkProjectController.getBuildList(dto);

        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getBuildList】获取项目楼栋信息失败", e);
        }
    }

    /**
     * <desc>
     * 获取项目楼栋的单元信息列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/08
     */
    @ResponseBody
    @PostMapping(path = "/getUnitList")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_UNIT_GET_LIST_LOG_DESC)
    public Object getUnitList() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String responseTimestamp = new Date().getTime() + "";
            dto.setResponseTimestamp(responseTimestamp);
            if (dto == null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getBuildNum())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
            }
            if (StringUtils.isBlank(dto.getCurrentPage())) {
                dto.setCurrentPage("1");
            }
            if (StringUtils.isBlank(dto.getPageSize())) {
                dto.setPageSize("15");
            }
            //如果为人脸识别API则需鉴权
//            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
//                //权限判断
//                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
//                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
//                }
//                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
//            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            if (dto.getDeviceType() != null && dto.getDeviceType().equals(SdkSourceTypeEnum.CLOUD_TALK.getType())) {
                request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            }
            return sdkCloudTalkProjectController.getUnitList(dto);

        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getUnitList】获取项目楼栋单元信息失败", e);
        }
    }

    /**
     * <desc>
     * 获取项目房间信息列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/08
     */
    @ResponseBody
    @PostMapping(path = "/getRoomList")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_ROOM_GET_LIST_LOG_DESC)
    public Object getRoomList() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String responseTimestamp = new Date().getTime() + "";
            dto.setResponseTimestamp(responseTimestamp);
            if (dto == null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getBuildNum())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
            }
            if (StringUtils.isBlank(dto.getCurrentPage())) {
                dto.setCurrentPage("1");
            }
            if (StringUtils.isBlank(dto.getPageSize())) {
                dto.setPageSize("15");
            }
            //如果为人脸识别API则需鉴权
//            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
//                //权限判断
//                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
//                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
//                }
//                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
//            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            if (dto.getDeviceType() != null && dto.getDeviceType().equals(SdkSourceTypeEnum.CLOUD_TALK.getType())) {
                request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            }
            return sdkCloudTalkProjectController.getRoomList(dto);

        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getRoomList】获取项目房间信息失败", e);
        }
    }

    /**
     * <desc>
     * 批量往存在的房间中添加住户
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author jiaqi.X
     * @createDate 2019/11/06
     */
    @ResponseBody
    @PostMapping(path = "/userRoom/add")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_BATCH_SAVE_USER_LOG_DESC)
    public Object addOrUpdateUserRooms() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", request.getAttribute("appId").toString() + "|" + dto.getProjectId() + "|" + dto.getDeviceType());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            String responseTimestamp = new Date().getTime() + "";
            if (dto.getDeviceType().equals("5")) {
                //云对讲
//                Map<String,Object> returnData = (HashMap) sdkCloudTalkProjectController.cloudTalkSDKAddUser(dto);
//                String code = returnData.get("code").toString();
//                if(code.equals("0")){
//                    return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),dto.getRequestId(),responseTimestamp,Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),responseTimestamp, dto.getAppSecret()), returnData);
//                }else{
//                    return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),dto.getRequestId(),responseTimestamp,Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),responseTimestamp, dto.getAppSecret()), (Object) returnData.get("modifyMessage").toString());
//                }
                return sdkCloudTalkProjectController.cloudTalkSDKAddUser(dto);
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), responseTimestamp, Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), dto.getRequestId(), responseTimestamp, dto.getAppSecret()));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_addOrUpdateRooms】添加或更新房间信息失败", e);
        }
    }

    /**
     * <desc>
     * 查询通行记录
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/11
     */
    @ResponseBody
    @PostMapping(path = "/getRecordInfo")
//    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_PASS_RECORD_LOG_DESC)
    public Object getPassRecord() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            String responseTimestamp = new Date().getTime() + "";
            dto.setResponseTimestamp(responseTimestamp);
            if (dto == null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getUserType()) || StringUtils.isBlank(dto.getRecordType()) || StringUtils.isBlank(dto.getDeviceType())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), request.getAttribute("requestId").toString(), responseTimestamp, "");
            }

            if (StringUtils.isBlank(dto.getCurrentPage())) {
                dto.setCurrentPage("1");
            }
            if (StringUtils.isBlank(dto.getPageSize())) {
                dto.setPageSize("15");
            }

            switch (SdkSourceTypeEnum.getByEquipType(Integer.valueOf(dto.getDeviceType()))) {
                //云对讲
                case CLOUD_TALK:
                    return sdkCloudTalkUserController.getPassRecord(dto);
                //二维码sdk
                case QR_CODE_SDK:
                    QrcodeSDKGetPassRecordDTO qrcodeSDKGetPassRecordDTO = HttpProtocolUtil.parseRequestParamToDTO(QrcodeSDKGetPassRecordDTO.class, request);
                    qrcodeSDKGetPassRecordDTO.setAppid(dto.getAppId());
                    qrcodeSDKGetPassRecordDTO.setAppsecret(dto.getAppSecret());
                    qrcodeSDKGetPassRecordDTO.setRequestId(dto.getRequestId());
                    qrcodeSDKGetPassRecordDTO.setResponseTimestamp(dto.getResponseTimestamp());
                    return sdkQrCodeController.getPassRecord(qrcodeSDKGetPassRecordDTO);
                //人脸识别sdk
                case FACE_SDK:
                    //权限判断
                    OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
                    operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
                    operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
                    OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
                    if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
                        return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
                    }
                    dto.setFaceMark("1");
                    request.setAttribute("portType", LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
                    return sdkFaceRecognitionController.getPassRecord(dto);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getRecordInfo】查询通行记录失败", e);
        }
    }

    /**
     * <desc>
     * 添加或更新多媒体资源信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/11
     */
    @ResponseBody
    @PostMapping(path = "/addOrUpdateMedia")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_MEDIA_ADD_OR_UPDATE_LOG_DESC)
    public Object addOrUpdateMedia() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudTalkSDKServerMediaDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerMediaDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            String responseTimestamp = new Date().getTime() + "";
            dto.setResponseTimestamp(responseTimestamp);
            if (StringUtils.isBlank(dto.getDeviceType())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
            }

            switch (dto.getDeviceType()) {
                //云对讲
                case "5":
                    return sdkCloudTalkMediaController.cloudTalkSDKAddOrUpdateMedia(dto);
                case "7":
                    //权限判断
                    OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
                    operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
                    operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
                    OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
                    if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
                        return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
                    }
                    request.setAttribute("portType", LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
                default:
            }
            return sdkCloudTalkMediaController.cloudTalkSDKAddOrUpdateMedia(dto);
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_addOrUpdateMedia】添加或更新多媒体资源信息失败", e);
        }
    }

    /**
     * <desc>
     * 添加访客
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/18
     */
    @ResponseBody
    @PostMapping(path = "/addVisitorInfo")
    @LoggerInfo(operateDesc = LogDescConstant.SAVE_VISITOR_INFO_DESC)
    public Object addVisitor() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            PropertyAddVisitorDTO dto = HttpProtocolUtil.parseRequestParamToDTO(PropertyAddVisitorDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            String responseTimestamp = new Date().getTime() + "";
            if (dto == null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getIntervieweeName()) || StringUtils.isBlank(dto.getVisitorName())
                    || StringUtils.isBlank(dto.getEffectiveTime()) || StringUtils.isBlank(dto.getDeviceType())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
            }
            //校验所传地址在该项目下是否存在
            Map<String, Object> map = iFaceSDKVisitorServiceClient.getAddressInfo(dto);
            if (map == null || map.isEmpty()) {
                return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_NOT_EXIST_ROOMNUM_ERR.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
            }
            //校验访客姓名及被拜访访客姓名的字段长度
            if (dto.getVisitorName().length() > 32 || dto.getIntervieweeName().length() > 32) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_VISITOR_NAME_ERR.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
            }
            if (dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())) {
                if (StringUtils.isBlank(dto.getRoomId()) || StringUtils.isBlank(dto.getBuildId()) || StringUtils.isBlank(dto.getUnitId())
                        || StringUtils.isBlank(dto.getImageStr())) {
                    return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
                }
                //权限判断
                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
                operateDeveloperAuthDeviceAuthListDTO.setUserId(dto.getAppId());
                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
                }
            } else {
                if (StringUtils.isBlank(dto.getRoomNum()) || StringUtils.isBlank(dto.getBuildNum()) || StringUtils.isBlank(dto.getUnitNum())) {
                    return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
                }
                dto.setBuildId(map.get("buildId").toString());
                dto.setUnitId(map.get("unitId").toString());
                dto.setRoomId(map.get("roomId").toString());
            }
            return sdkFaceRecognitionController.addVisitor(dto);
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_addVisitorInfo】添加访客失败", e);
        }
    }

    public static void main(String[] args) {
        String s = null;
        switch (s) {
            //云对讲
            case "5":
                System.out.println("2");
            default:
                System.out.println("1");
        }
    }

    /**
     * <desc>
     * 冻结/解冻用户状态
     * <desc/>
     *
     * @return MessageVO   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/11/19
     */
    @ResponseBody
    @PostMapping(path = "/modifyUserStatus")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_FACE_USER_PROJECT_STATUS_LOG_DESC)
    public Object modifyUserStatus() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            dto.setAppId(request.getAttribute("appId").toString());
            dto.setAppSecret(request.getAttribute("appSecret").toString());
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);

            String responseTimestamp = new Date().getTime() + "";
            if (StringUtils.isBlank(dto.getProjectId())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
            }
            switch (dto.getDeviceType()) {
                //云对讲
                case "5":
                    CloudTalkSDKServerUserStatusDTO userStatusDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerUserStatusDTO.class, request);
                    userStatusDTO.setAppSecret(dto.getAppSecret());
                    userStatusDTO.setResponseTimestamp(responseTimestamp);
                    userStatusDTO.setRequestId(dto.getRequestId());
                    return sdkCloudTalkProjectController.modifyUserStatus(userStatusDTO);
                default:
                    //公共
                    AppUserUpdateUserProjectStatusDTO appUserUpdateUserProjectStatusDTO = HttpProtocolUtil.parseRequestParamToDTO(AppUserUpdateUserProjectStatusDTO.class, request);
                    appUserUpdateUserProjectStatusDTO.setProjectId(request.getAttribute("projectId").toString());
                    appUserUpdateUserProjectStatusDTO.setAppSecret(dto.getAppSecret());
                    appUserUpdateUserProjectStatusDTO.setResponseTimestamp(responseTimestamp);
                    appUserUpdateUserProjectStatusDTO.setRequestId(dto.getRequestId());
                    //权限判断
//                    OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                    operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                    operateDeveloperAuthDeviceAuthListDTO.setProjectId(appUserUpdateUserProjectStatusDTO.getProjectId());
//                    OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                    if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                        return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
//                    }
                    return sdkFaceRecognitionController.modifyUserStatus(appUserUpdateUserProjectStatusDTO);
            }
        } catch (Exception e) {
            throw new DataAccessException("【SDK_基类_modifyUserStatus】冻结/解冻用户状态异常", e);
        }
    }

    /**
     * <desc>
     * 机器人调试工具开发者登录
     * </desc>
     *
     * @return
     * @Author Zhu.yj
     * @createDate 2020/8/25
     */
    @UnAuthAccessRequired
    @RequestMapping(value = "robotGoDeveloperLogin", method = RequestMethod.POST)
    public Object robotGoDeveloperLogin(String encryptScript, String appId, String loginType) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
        String responseTimestamp = new Date().getTime() + "";
        Date nowDate = new Date();
        Map<String, Object> resultMap = new HashMap<>();
        PropertyUserInfoPO propertyUserInfoPO = new PropertyUserInfoPO();
        try {
            if (StringUtils.isBlank(loginType) || StringUtils.isBlank(appId) || StringUtils.isBlank(encryptScript)) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), "", responseTimestamp, "");
            }
            //开发者登录
            if ("1".equals(loginType)) {
                //当登录类型位开发者登录的时候
                propertyUserInfoPO = iSDKUserServiceClient.getPropertyUserByUserName(appId);
                if (propertyUserInfoPO == null || StringUtils.isBlank(propertyUserInfoPO.getAppsecret())) {
                    return new SDKMessageVO(AppErrorCodeEnum.USER_NOT_EXIST.getErrorCode(), "", responseTimestamp, "");//此时没有加密签名直接明文返回报错信息
                }
                propertyUserInfoPO.setAppsecret(APP_SECRET);
                if (propertyUserInfoPO.getStatus() != DataStatusEnum.NORMAL.getType()) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(AppErrorCodeEnum.ACCOUNT_BAN_ERROR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
                //未开通机器人调试开关
                if (propertyUserInfoPO.getRobotSwitch() == 0) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.PUB_ROBOT_SWITCH_CLOSE_ERR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
                //不在有效期内
                if (nowDate.before(propertyUserInfoPO.getEffectStartTime()) || nowDate.after(propertyUserInfoPO.getEffectEndTime())) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.USER_ACCOUNT_EXPIRE_ERR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
                //筛选只有机器人开发者有权限
                if (!propertyUserInfoPO.getRoleId().equals(PropertyPublicRoleEnum.ROBOT_DEVELOPER.getRoleId())) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.USER_AUTH_ERROR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
            }
            if ("2".equals(loginType)) {
                OperateUserInfoPO operateUserInfoPO = iOperateUserInfoServiceClient.getUserByUserName(appId);
                //把工程人员的信息存到propertyUserInfo中，为方便存储缓存
                if (operateUserInfoPO == null) {
                    //此时没有加密签名直接明文返回报错信息
                    return new SDKMessageVO(AppErrorCodeEnum.USER_NOT_EXIST.getErrorCode(), "", responseTimestamp, "");
                }
                //工程账号不再有效期内
                if (operateUserInfoPO.getAuthType() == 1 && (nowDate.before(operateUserInfoPO.getAuthStartTime()) || nowDate.after(operateUserInfoPO.getAuthEndTime()))) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.USER_ACCOUNT_EXPIRE_ERR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
                BeanUtils.copyProperties(operateUserInfoPO, propertyUserInfoPO);
                propertyUserInfoPO.setAppsecret(APP_SECRET);
                if (null == propertyUserInfoPO.getRoleId()) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.USER_AUTH_ERROR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }

                List<String> roleIdList = StringHandlerUtil.splitStringList(propertyUserInfoPO.getRoleId());
                if (!roleIdList.contains(OperateSystemSetUpEnum.ENGINNER.getType().toString())) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.USER_AUTH_ERROR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
                //工程人员设置roleId为1,否则拿不到数据
                propertyUserInfoPO.setRoleId(OperateSystemSetUpEnum.ENGINNER.getType().toString());
            }
            CloudDeviceSDKDTO dto = new CloudDeviceSDKDTO();
            String encryptResult = DesEncryptUtil.aesDecrypt(encryptScript, propertyUserInfoPO.getAppsecret());
            if (StringUtils.isBlank(encryptResult)) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_PARAM_APPID_APPSECRET_ERR.getErrorCode(), "", responseTimestamp, "");//此时没有加密签名直接明文返回报错信息
            }
            Map<String, Object> params;
            JSONObject jsStr = JSONObject.parseObject(encryptResult);//入参转json
            String requestId;
            try {
                requestId = jsStr.get("requestId") == null ? "" : jsStr.get("requestId").toString();
                String timestamp = jsStr.get("timestamp") == null ? "" : jsStr.get("timestamp").toString();
                request.setAttribute("requestId", requestId);
                request.setAttribute("timestamp", timestamp);
                JSONObject protocol = JSONObject.parseObject(jsStr.get("protocol").toString());
                request.setAttribute("version", protocol.get("version") == null ? "" : protocol.get("version").toString());
                JSONObject client = JSONObject.parseObject(jsStr.get("client").toString());
                JSONObject param = JSONObject.parseObject(jsStr.get("param").toString());
                params = JsonUtil.toObject(protocol.toString(), HashMap.class);
                params.putAll(JsonUtil.toObject(client.toString(), HashMap.class));
                params.putAll(JsonUtil.toObject(param.toString(), HashMap.class));

                //保存生成操作日志所需信息 详细描述和接口类别
//                request.setAttribute("remark", "appId:"+appId + "|" + "appSecret:"+params.get("appSecret") + "robotId:"+param.get("robotId"));
//                request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
//                dto.setAppId(appId);
//                dto.setAppSecret(params.get("appSecret").toString());
                params.remove("appSecret");

                //验签
                String sign = jsStr.get("sign").toString();
                if (!Md5EncryptUtil.checkSDKV2Sign(params, sign, requestId, timestamp, propertyUserInfoPO.getAppsecret())) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_MD5_ERROR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
            } catch (Exception e) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_INPUT_PARAM_ERR.getErrorCode(), "", responseTimestamp, "");//json格式解析失败
            }
            String password = params.get("password") == null ? null : params.get("password").toString();
            String robotUnique = params.get("robotUnique") == null ? null : params.get("robotUnique").toString();
            if (StringUtils.isBlank(password) || StringUtils.isBlank(robotUnique)) {
                return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
            }
            //验证密码是否正确
            password = UserTokenUtil.getPassword(password, APP_USER_TOKEN_KEY);
            if (!Md5.En(password).equals(propertyUserInfoPO.getPassword())) {
                return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(AppErrorCodeEnum.USER_NOT_EXIST.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
            }
            //获取登录个
            PropertyUserInfoPO userRetrieveInfoPO = (PropertyUserInfoPO) redisService.getObject(RedisConstant.REDIS_CLOUDDEVICE_SDK_DEVELOPER_CACHE + propertyUserInfoPO.getUserId(), PropertyUserInfoPO.class);
            //做登录个数限制
            if (userRetrieveInfoPO == null) {
                userRetrieveInfoPO = new PropertyUserInfoPO();
            }
            List<String> robotUniques = userRetrieveInfoPO.getRobotUniques();
            if (robotUniques == null) {
                robotUniques = new ArrayList<>();
                robotUniques.add(robotUnique);
            }
            if (!robotUniques.contains(robotUnique)) {
                robotUniques.add(robotUnique);
            }
            if ("1".equals(loginType)) {
                if (robotUniques.size() > propertyUserInfoPO.getLoginCount()) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(AppErrorCodeEnum.ROBOT_LOGIN_COUNT_ERR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
                resultMap.put("statTime", dateFormat.format(propertyUserInfoPO.getEffectStartTime()));
                resultMap.put("stopTime", dateFormat.format(propertyUserInfoPO.getEffectEndTime()));
            } else {
                resultMap.put("statTime", "永久有效");
                resultMap.put("stopTime", "永久有效");
            }
            propertyUserInfoPO.setRobotUniques(robotUniques);
            propertyUserInfoPO.setLoginType(loginType);
            String token = iCloudTalkSDKAppUserServiceClient.robotGoDeveloperLogin(propertyUserInfoPO, null);
            List<AppProjectRobotInfoVO> projectRobotInfoVOS = iOperatePropertyAccountServiceClient.getProjectRobotInfoByDeveloper(propertyUserInfoPO.getUserId(), loginType);
            if ("1".equals(loginType)) {
                for (AppProjectRobotInfoVO VO : projectRobotInfoVOS) {
                    Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(VO.getProjectId(), propertyUserInfoPO.getUserId());
                    Integer robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");

                    //启用白名单1
                    if ("1".equals(robotWhiteListAuthStatus + "")) {
                        //对接方式为云对接，又无项目及机器人信息
                        if ("1".equals(propertyUserInfoPO.getDockMode()) && projectRobotInfoVOS.isEmpty()) {
                            return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.USER_AUTH_ERROR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                        }
                    }
                    //没有启用白名单0
                    if ("0".equals(robotWhiteListAuthStatus + "")) {
                        List<String> emptyList = new ArrayList<>();
                        VO.setRobotIdList(emptyList);
                    }
                }
            }
            resultMap.put("token", token);
            resultMap.put("projectList", projectRobotInfoVOS);
            return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), requestId, responseTimestamp, "", resultMap), propertyUserInfoPO.getAppsecret());
        } catch (Exception e) {
            throw new DataAccessException("【SDK_基类_robotGoDeveloperLogin】机器人调试工具开发者登录失败", e);
        }
    }

    /**
     * <desc>
     * 获取项目列表
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate 2020/8/3
     */
    @ResponseBody
    @PostMapping("getProjectList")
    public Object getProjectList(String token, HttpServletRequest request) {
        try {
            String responseTimestamp = new Date().getTime() + "";
            PropertyUserInfoPO propertyUserInfoPO = iCloudTalkSDKAppUserServiceClient.developerRetrieve(token);
            List<AppProjectRobotInfoVO> projectInfoVOList = iOperatePropertyAccountServiceClient.getProjectRobotInfoByDeveloper(propertyUserInfoPO.getUserId(), propertyUserInfoPO.getLoginType());

            if ("4".equals(propertyUserInfoPO.getRoleId()) || "7".equals(propertyUserInfoPO.getRoleId()))
                for (AppProjectRobotInfoVO VO : projectInfoVOList) {
                    Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(VO.getProjectId(), propertyUserInfoPO.getUserId());
                    Integer robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");

                    //没有启用白名单0
                    if ("0".equals(robotWhiteListAuthStatus + "")) {
                        List<String> emptyList = new ArrayList<>();
                        VO.setRobotIdList(emptyList);
                    }
                }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), request.getAttribute("requestId").toString(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), request.getAttribute("requestId").toString(), responseTimestamp,
                            propertyUserInfoPO.getAppsecret()), projectInfoVOList);
        } catch (Exception e) {
            throw new DataAccessException("【SDK_基类_getProjectList】获取项目列表失败", e);
        }
    }

//    /**
//     * <desc>
//     *      切换项目
//     * </desc>
//     *
//     * @return
//     * @Author Zhu.yj
//     * @createDate  2020/8/4
//     */
//    @ResponseBody
//    @PostMapping("changeProject")
//    public Object changeProject(String token, String projectId, HttpServletRequest request){
//        try{
//            String responseTimestamp = new Date().getTime()+"";
//            Map<String, Object> resultMap = new HashMap<>();
//            PropertyUserInfoPO propertyUserInfoPO = iCloudTalkSDKAppUserServiceClient.developerRetrieve(token);
//            if (StringUtils.isBlank(projectId)){
//                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),request.getAttribute("requestId").toString(), responseTimestamp,
//                        Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),request.getAttribute("requestId").toString(),responseTimestamp,
//                                propertyUserInfoPO.getAppsecret()));
//            }
//
//            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
//        }catch (Exception e){
//            throw new DataAccessException("【APP_切换项目】切换项目失败", e);
//        }
//    }

    /**
     * <desc>
     * 机器人APP退出登录
     * </desc>
     *
     * @param token       登录token
     * @param robotUnique 机器人唯一码
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/10/15
     */
    @ResponseBody
    @PostMapping("logout")
    public Object robotLogout(String token, String robotUnique, HttpServletRequest request) {
        try {
            String responseTimestamp = new Date().getTime() + "";
            robotUnique = request.getAttribute("robotUnique") == null ? null : request.getAttribute("robotUnique").toString();
            PropertyUserInfoPO propertyUserInfoPO = iCloudTalkSDKAppUserServiceClient.developerRetrieve(token);
            String cacheKey = String.format("%s%s", RedisConstant.REDIS_CLOUDDEVICE_SDK_DEVELOPER_CACHE, propertyUserInfoPO.getUserId());
            List<String> robotUniques = propertyUserInfoPO.getRobotUniques();
            if (robotUniques != null && robotUniques.size() > 0) {
                robotUniques.remove(robotUnique);
                if (robotUniques.size() > 0) {
                    propertyUserInfoPO.setRobotUniques(robotUniques);
                    redisService.set(cacheKey, RedisConstant.REDIS_ROBOT_USER_CACHE_TIME, propertyUserInfoPO);
                } else {
                    redisService.del(cacheKey);
                }
            } else {
                redisService.del(cacheKey);
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), request.getAttribute("requestId").toString(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), request.getAttribute("requestId").toString(), responseTimestamp,
                            propertyUserInfoPO.getAppsecret()));
        } catch (Exception e) {
            throw new DataAccessException("【SDK基类_机器人退出登录】退出登录失败", e);
        }
    }

    /**
     * <desc>
     * 获取单梯多梯标记
     * </desc>
     *
     * @Author Zhu.yj
     * @createDate 2020/9/7
     */
//    接口暂时注释，下个版本添加
//    @RequestMapping(value = "getElevatorFlag", method = RequestMethod.POST)
    public Object getElevatorFlag(String token, String robotId, HttpServletRequest request) {
        try {
            String responseTimestamp = System.currentTimeMillis() + "";
            Map<String, Object> resultMap = new HashMap<>();
            robotId = request.getAttribute("robotId") == null ? null : request.getAttribute("robotId").toString();
            PropertyUserInfoPO propertyUserInfoPO = iCloudTalkSDKAppUserServiceClient.developerRetrieve(token);
            if (robotId == null) {
                resultMap.put("flag", MultiElevatorAuthEnum.NONE_ELEVATOR_AUTH.getType());
                return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), request.getAttribute("requestId").toString(), responseTimestamp,
                        Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), request.getAttribute("requestId").toString(), responseTimestamp,
                                request.getAttribute("appSecret").toString()), resultMap);
            }
            resultMap = iCloudElevatorSDKRobotServiceClient.getElevatorFlag(robotId);
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), request.getAttribute("requestId").toString(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), request.getAttribute("requestId").toString(), responseTimestamp,
                            request.getAttribute("appSecret").toString()), resultMap);
        } catch (Exception e) {
            throw new DataAccessException("【SDK基类_getElevatorFlag】获取单梯多梯标记失败", e);
        }
    }

    /**
     * <desc>
     * 设置消息回调的url地址
     * </desc>
     *
     * @Author chengshican
     * @Date 2020-11-19 19:27
     * @Param updateMessageCallbackRrl 用户设置消息推送的接口url
     * @Return
     * @Exception
     */
    @ResponseBody
    @PostMapping("/updateUserProjectByUserId")
    public Object updateUserProjectByUserId(String callbackUrl, String token) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            callbackUrl = request.getAttribute("callbackUrl") == null ? null : request.getAttribute("callbackUrl").toString();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            PropertyUserInfoPO propertyUserInfoPO = iCloudTalkSDKAppUserServiceClient.developerRetrieve(token);
            //验签
            if (StringUtils.isBlank(callbackUrl) || StringUtils.isBlank(callbackUrl)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            iCloudTalkSDKAppUserServiceClient.updateUserProjectByUserId(callbackUrl, propertyUserInfoPO.getCurrentProjectId(), propertyUserInfoPO.getUserId());
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【SDK基类_updateUserProjectByUserId】设置消息回调的url地址失败", e);
        }
    }


    /**
     * <desc>
     * 触发向第三方推送api接口文档更新接口（开放平台推送更新按钮）
     * </desc>
     *
     * @Author chengshican
     * @Date 2020-11-23 9:50
     * @Param 0 云对讲 1 蓝牙SDK  2 二维码SDK 3 云电梯API 4 云门禁API 5 人脸识别API 6 机器人无感通行 7 机器人无感通行 8 机器人云门禁 9 离线二维码SDK
     * *         10微信小插件二维码  11微信小插件蓝牙 12 在线二维码API
     * @Param newVersion 版本号
     * @Return
     * @Exception
     */
    @RequestMapping(value = "/pushMessage", method = RequestMethod.POST)
    @ResponseBody
    @UnAuthAccessRequired
    public Object sendPushMessage(String type, String newVersion) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            type = request.getAttribute("type") == null ? null : request.getAttribute("type").toString();
            newVersion = request.getAttribute("newVersion") == null ? null : request.getAttribute("newVersion").toString();

            //验签
            if (StringUtils.isBlank(type) || StringUtils.isBlank(type)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //验签
            if (StringUtils.isBlank(String.valueOf(newVersion)) || StringUtils.isBlank(String.valueOf(newVersion))) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Integer num = isdkServerProjectServiceClient.getSendMessgeUrl(type, Double.parseDouble(newVersion));
            if (num > 0) {
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            } else {
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【SDK基类_sendPushMessage】触发向第三方推送api接口文档更新接口失败", e);
        }
    }


    /**
     * <desc>
     * 用户确认接受更新接口（用户接受更新时调用此接口回传信息）
     * </desc>
     *
     * @Author chengshican
     * @Date 2020-11-23 9:58
     * @Param
     * @Return
     * @Exception
     */
    @RequestMapping("/pushMessageCallBack")
    @ResponseBody
    @UnAuthAccessRequired
    public Object sendPushMessageCallBack(SendPushMessageDTO dto) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto = HttpProtocolUtil.parseRequestParamToDTO(SendPushMessageDTO.class, request);
            //验签
            if (StringUtils.isBlank(dto.getLoginUserId()) || dto == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Integer integer = isdkServerProjectServiceClient.updateSDKApiVersion(dto);
            if (integer > 0) {
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            } else {
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【SDK基类_sendPushMessageCallBack】用户确认接受更新接口失败", e);
        }
    }


    /**
     * <desc>
     * 测试用户接受更新接口
     * </desc>
     *
     * @Author chengshican
     * @Date 2020-11-23 9:58
     * @Param
     * @Return
     * @Exception
     */
    @RequestMapping("/sendPushMessageCallBackTest")
    @ResponseBody
    @UnAuthAccessRequired
    public Object sendPushMessageCallBackTest(@RequestParam(required = false, defaultValue = "1") String id) {
        try {
            LOG.info("==1===========id=====>{}", id);
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String id1 = request.getParameter("id");
            LOG.info("===2==========id=====>{}", id1);
            return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【SDK基类_sendPushMessageCallBackTest】测试用户接受更新接口", e);
        }
    }
}

